package cn.tristenstudy.blog.util;

import org.commonmark.Extension;
import org.commonmark.ext.gfm.tables.TableBlock;
import org.commonmark.ext.gfm.tables.TablesExtension;
import org.commonmark.ext.heading.anchor.HeadingAnchorExtension;
import org.commonmark.node.Link;
import org.commonmark.node.Node;
import org.commonmark.parser.Parser;
import org.commonmark.renderer.html.AttributeProvider;
import org.commonmark.renderer.html.HtmlRenderer;

import java.util.*;

/**
 * MarkDown转html工具类
 *
 * @author xichen1.li
 * @date 2021-01-11 11:26
 */
public class MarkDownUtils {

    /**
     * markDown格式转换成HTML格式
     *
     * @param markDown markDown字符串
     * @return HTML语句
     */
    public static String markDownToHtml(String markDown) {
        Parser parser = Parser.builder().build();
        Node document = parser.parse(markDown);
        HtmlRenderer renderer = HtmlRenderer.builder().build();
        return renderer.render(document);
    }

    /**
     * 增加扩展（标题锚点，表格生成）
     *
     * @param markDown markDown字符串
     * @return HTML语句
     */
    public static String markDownToHtmlExtensions(String markDown) {
        //标题生成id
        Set<Extension> headingAnchorExtensions = Collections.singleton(HeadingAnchorExtension.create());
        //转换table的Html
        List<Extension> tablesExtension = Arrays.asList(TablesExtension.create());
        Parser parser = Parser.builder()
                .extensions(tablesExtension)
                .build();
        Node document = parser.parse(markDown);
        HtmlRenderer renderer = HtmlRenderer.builder()
                .extensions(headingAnchorExtensions)
                .extensions(tablesExtension)
                .attributeProviderFactory((context) -> new CustomAttributeProvider())
                .build();
        return renderer.render(document);
    }

    /**
     * 处理标签属性
     */
    static class CustomAttributeProvider implements AttributeProvider {
        @Override
        public void setAttributes(Node node, String s, Map<String, String> attributes) {
            //改变a标签的target属性为_blank
            if (node instanceof Link){
                attributes.put("target","_blank");
            }
            if (node instanceof TableBlock){
                attributes.put("class","ui celled table");
            }
        }
    }

}
